package com.yiwyn.process;

import com.yiwyn.annotation.Serialize;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.util.Set;


public class SerializeProcessor extends AbstractProcessor {


    private Elements elementUtils;


    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        elementUtils = processingEnv.getElementUtils();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        System.out.println("开始处理");
        Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(Serialize.class);
        for (Element element : elementsAnnotatedWith) {
            Serialize annotation = element.getAnnotation(Serialize.class);

            Name className = element.getSimpleName();

            String packageName = elementUtils.getPackageOf(element).getQualifiedName().toString();

            String fullClassName = packageName + "." + className;

            try {
                JavaFileObject file = processingEnv.getFiler().createClassFile(fullClassName);

                try (Writer writer = file.openWriter()) {
                    writer.write("package " + packageName + ";\n\n");
                    writer.write("import java.io.Serializable;\n\n");
                    writer.write("public class " + className + " implements Serializable {\n");
                    writer.write("    private static final long serialVersionUID = 1L;\n");  // 生成 serialVersionUID
                    writer.write("}\n");
                }

                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated serializable class: " + fullClassName);
            } catch (IOException e) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Generated serializable class: " + fullClassName);
            }
        }
        return true;
    }
}
